package guowei.guliauth.controller;

import com.alibaba.fastjson.TypeReference;
import guowei.common.constant.SessionInfo;
import guowei.common.utils.R;
import guowei.guliauth.feign.UserFeign;
import guowei.guliauth.service.WeiboService;
import guowei.common.vo.MemberVo;
import guowei.guliauth.vo.TokenOthers;
import guowei.guliauth.vo.WeiboToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class WeiboLogin {
    @Value("${weibo.clientid}")
    private String clientId;
    @Value("${weibo.clientsecret}")
    private String clientSecret;
    @Value("${weibo.granttype}")
    private String grantType;
    @Value("${weibo.redirecturi}")
    private String redirectUrI;

    @Autowired
    private UserFeign userFeign;

    @GetMapping("/oauth/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse httpServletResponse){
        System.out.println(code);

//        1.code换取token
        WeiboToken weiboToken = new WeiboToken();
        weiboToken.setCode(code);
        weiboToken.setClientId(clientId);
        weiboToken.setClientSecret(clientSecret);
        weiboToken.setRedirectUrI(redirectUrI);
        WeiboService weiboService = new WeiboService();

        TokenOthers tokenOthers = weiboService.getToken(weiboToken);

//        保存用户信息到user表中
        R user = userFeign.saveWeiboUser(tokenOthers);
        MemberVo memberVo = (MemberVo) user.getData("data", new TypeReference<MemberVo>() {});

//  服务端得到session的信息，需要JSESSIONID才行
        session.setAttribute(SessionInfo.SESSION_PREFIX,memberVo);

        return "redirect://ganjiuwanle.com";
    }
}
